package development;

import particle.core.platform.IPlatformPictureImportEventHandler;
import particle.core.platform.Platform;
import particle.core.platform.PlatformPictureImportEvent;
import particle.core.tools.ByteBuffer;
import particle.core.view.assets.Image;
import state.GameAlert;
import state.GameForm;
import state.GameImage;
import state.Graphics;
import state.Key;
import state.font.FontManager;
import state.font.ImageFont;
import state.socket.DataPackage;
import state.util.GameColor;
import state.util.Hashtable;
import state.util.ImageUtil;
import state.util.array.ByteArray;
import state.util.array.StringArray;
import development.socket.ProtocolConstants;
import development.socket.SocketClientUtil;

public class FrmChooseAvatar extends GameForm implements IPlatformPictureImportEventHandler {
  private final int NUMBER_OF_AVATAR_PER_PAGE = 16;

  public StringArray categories;
  public int[] numberOfAvatarByCategory;
  public int categoryChoosedIndex;
  
  public StringArray currentPageAvatarIds;
  public boolean[] requestedAvatar;
  public int avatarChooseIndex;
  
  public boolean isInCategoryList;
  public int currentPage;

  private GameImage leftArrowImage;
  private GameImage leftFocusArrowImage;

  private ImageFont text13;
  private ImageFont text8;

  private int maxPage;
  private int NUMBER_AVATAR_OF_ROW;
  
  private static GameForm singleton;
  
  public static GameForm instance() {
    if (singleton == null) {
      singleton = new FrmChooseAvatar();
    }
    return singleton;
  }

  public void init(Hashtable parameters) {
    isInCategoryList = true;
    avatarChooseIndex = 0;
    SocketClientUtil.requestAvatarCategoryList();
    
    if (Constants.IS_240x320_SCREEN) {
      NUMBER_AVATAR_OF_ROW = 4;
    } else {
      NUMBER_AVATAR_OF_ROW = 6;
    }
    leftArrowImage = ImageUtil.getImage(Constants.NEW_IMAGE_CATEGORY, "muiten.png");
    leftFocusArrowImage = ImageUtil.getImage(Constants.NEW_IMAGE_CATEGORY, "muiten_focus.png");
    
    categories = StringArray.create(0);
    numberOfAvatarByCategory = new int[0];
    currentPageAvatarIds = StringArray.create(0);
    requestedAvatar = new boolean[0];

    text13 = FontManager.getFont(FontManager.FONT_SIZE_13);
    text8 = FontManager.getFont(FontManager.FONT_SIZE_8);
    _manager.enableTouchPad();
  }
  
  public void setCategoryList(StringArray categories1, int[] numberOfAvatarByCategory1) {
    this.categories = categories1;
    this.numberOfAvatarByCategory = numberOfAvatarByCategory1;
  }

  private void draw240x320(Graphics g) {
    if (isInCategoryList) {
      if (categories.len() > 0) {
        for (int i = 0; i < categories.len(); i++) {
          int colour;
          g.setColor(GameColor.BLACK_CODE);
          g.drawLine(10, 35 + 21 * i, Constants.SCREEN_WIDTH - 10, 35 + 21 * i);
          if (i == categoryChoosedIndex) {
            g.drawImage(leftFocusArrowImage, 12, 42 + 21 * i, Constants.TOP_LEFT_ANCHOR);
            colour = GameColor.RED2_CODE;
          } else {
            g.drawImage(leftArrowImage, 12, 42 + 21 * i, Constants.TOP_LEFT_ANCHOR);
            colour = GameColor.BLACK_CODE;
          }
          text8.drawString2(g, categories.array[i] + " (" + numberOfAvatarByCategory[i] + ")", colour, 22, 38 + 21 * i, Constants.TOP_LEFT_ANCHOR);
        }
      } else {
        DrawUtils.drawHozPopup(g, 183, 28, 82);
        text8.drawString2(g, "Đang cập nhật danh sách avatar...", GameColor.WHITE_CODE, Constants.SCREEN_WIDTH / 2, 115, Constants.TOP_HCENTER_ANCHOR);
        text8.drawString2(g, "Xin vui lòng chờ trong giây lát", GameColor.WHITE_CODE, Constants.SCREEN_WIDTH / 2, 133, Constants.TOP_HCENTER_ANCHOR);
      }
      DrawUtils.setBottomBar(_manager, "Up ảnh", "Chọn avatar", "Trở về");
    } else {
      for (int i = 0; i < currentPageAvatarIds.len(); i++) {
        GameImage avatar = getAvatar(currentPageAvatarIds.array[i], i);
        if (avatar != null) {
          g.drawImage(avatar, 5 + 55 * (i % NUMBER_AVATAR_OF_ROW), 40 + 55 * (i / NUMBER_AVATAR_OF_ROW), Constants.TOP_LEFT_ANCHOR);
        }
      }

      if (maxPage > 1) {
        for (int i = 0; i < maxPage; i++) {
          if (i == currentPage) {
            text13.drawString2(g, String.valueOf(i + 1), GameColor.GREEN_CODE, 30 + i * 15, 270, Constants.TOP_LEFT_ANCHOR);
          } else {
            text13.drawString2(g, String.valueOf(i + 1), GameColor.WHITE_CODE, 30 + i * 15, 270, Constants.TOP_LEFT_ANCHOR);
          }
        }
      }

      // Vẽ khung chọn
      g.setColor(GameColor.RED2_CODE);
      g.drawRect(5 + 55 * (avatarChooseIndex % NUMBER_AVATAR_OF_ROW), 40 + 55 * (avatarChooseIndex / NUMBER_AVATAR_OF_ROW), 50, 50);
      g.drawRect(4 + 55 * (avatarChooseIndex % NUMBER_AVATAR_OF_ROW), 39 + 55 * (avatarChooseIndex / NUMBER_AVATAR_OF_ROW), 52, 52);
      text8.drawString2(g, "CHỌN AVATAR - " + categories.array[categoryChoosedIndex], GameColor.WHITE_CODE, Constants.SCREEN_WIDTH / 2, 10, Constants.CENTER_ANCHOR);
      DrawUtils.setBottomBar(_manager, "Up ảnh", "Chọn", "Trở về");
    }
  }
  
  public GameImage getAvatar(String avatarId, int index) {
    GameImage avatar = AvatarCache.getAvatar(avatarId);
    if (avatar == null) {
      if (!requestedAvatar[index]) {
        SocketClientUtil.getAvatar("", avatarId);
        requestedAvatar[index] = true;
      }
      return null;
    }
    return avatar;
  }

  private void draw320x240(Graphics g) {
    if (isInCategoryList) {
      if (categories.len() > 0) {
        for (int i = 0; i < categories.len(); i++) {
          int colour;
          g.setColor(GameColor.WHITE_CODE);
          g.drawLine(10, 35 + 21 * i, Constants.SCREEN_WIDTH - 10, 35 + 21 * i);
          if (i == categoryChoosedIndex) {
            g.drawImage(leftFocusArrowImage, 12, 42 + 21 * i, Constants.TOP_LEFT_ANCHOR);
            colour = GameColor.YELLOW_CODE;
          } else {
            g.drawImage(leftArrowImage, 12, 42 + 21 * i, Constants.TOP_LEFT_ANCHOR);
            colour = GameColor.WHITE_CODE;
          }
          text8.drawString2(g, categories.array[i] + " (" + numberOfAvatarByCategory[i] + ")", colour, 22, 38 + 21 * i, Constants.TOP_LEFT_ANCHOR);
        }
      } else {
        DrawUtils.drawHozPopup(g, 183, 68, 82);
        text8.drawString2(g, "Đang cập nhật danh sách avatar...", GameColor.WHITE_CODE, Constants.SCREEN_WIDTH / 2, 115, Constants.TOP_HCENTER_ANCHOR);
        text8.drawString2(g, "Xin vui lòng chờ trong giây lát", GameColor.WHITE_CODE, Constants.SCREEN_WIDTH / 2, 133, Constants.TOP_HCENTER_ANCHOR);
      }
      DrawUtils.setBottomBar(_manager, "Up ảnh", "Chọn avatar", "Trở về");
    } else {
      for (int i = 0; i < currentPageAvatarIds.len(); i++) {
        GameImage avatar = getAvatar(currentPageAvatarIds.array[i], i);
        if (avatar != null) {
          g.drawImage(avatar, 5 + 52 * (i % NUMBER_AVATAR_OF_ROW), 40 + 55 * (i / NUMBER_AVATAR_OF_ROW), Constants.TOP_LEFT_ANCHOR);
        }
      }

      if (maxPage > 1) {
        for (int i = 0; i < maxPage; i++) {
          if (i == currentPage) {
            text13.drawString2(g, String.valueOf(i + 1), GameColor.GREEN_CODE, 30 + i * 15, 270, Constants.TOP_LEFT_ANCHOR);
          } else {
            text13.drawString2(g, String.valueOf(i + 1), GameColor.WHITE_CODE, 30 + i * 15, 270, Constants.TOP_LEFT_ANCHOR);
          }
        }
      }

      // Vẽ khung chọn
      g.setColor(GameColor.RED2_CODE);
      g.drawRect(5 + 52 * (avatarChooseIndex % NUMBER_AVATAR_OF_ROW), 40 + 55 * (avatarChooseIndex / NUMBER_AVATAR_OF_ROW), 50, 50);
      g.drawRect(4 + 52 * (avatarChooseIndex % NUMBER_AVATAR_OF_ROW), 39 + 55 * (avatarChooseIndex / NUMBER_AVATAR_OF_ROW), 52, 52);
      text8.drawString2(g, "CHỌN AVATAR - " + categories.array[categoryChoosedIndex], GameColor.WHITE_CODE, Constants.SCREEN_WIDTH / 2, 10, Constants.CENTER_ANCHOR);
      DrawUtils.setBottomBar(_manager, "Up ảnh", "Chọn", "Trở về");
    }
  }

  public void draw(Graphics g) {
    DrawUtils.drawBackground(g);
    DrawUtils.drawTopBar(g);
    if (Constants.IS_240x320_SCREEN) {
      draw240x320(g);
    } else {
      draw320x240(g);
    }
  }

  public void keyReleased(int keyCode) {
    switch (keyCode) {
    case Key.UP:
      if (isInCategoryList) {
        if (categoryChoosedIndex > 0) {
          categoryChoosedIndex--;
        }
      } else {
        int backAvatar = avatarChooseIndex - NUMBER_AVATAR_OF_ROW;
        if (backAvatar > -1) {
          avatarChooseIndex = backAvatar;
        }
      }
      break;
    case Key.DOWN:
      if (isInCategoryList) {
        if (categoryChoosedIndex < categories.len() - 1) {
          categoryChoosedIndex++;
        }
      } else {
        int nextAvatar = avatarChooseIndex + NUMBER_AVATAR_OF_ROW;
        if (nextAvatar < currentPageAvatarIds.len()) {
          avatarChooseIndex = nextAvatar;
        }
      }
      break;
    case Key.RIGHT:
      if (!isInCategoryList) {
        int nextAvatar = avatarChooseIndex + 1;
        if (nextAvatar < currentPageAvatarIds.len()) {
          avatarChooseIndex = nextAvatar;
        }
      }
      break;
    case Key.LEFT:
      if (!isInCategoryList) {
        int backAvatar = avatarChooseIndex - 1;
        if (backAvatar > -1) {
          avatarChooseIndex = backAvatar;
        }
      }
      break;
    case Key.FIRE:
      if (isInCategoryList) {
        maxPage = numberOfAvatarByCategory[categoryChoosedIndex] / NUMBER_OF_AVATAR_PER_PAGE;
        if (numberOfAvatarByCategory[categoryChoosedIndex] > maxPage * NUMBER_OF_AVATAR_PER_PAGE) {
          maxPage++;
        }
        isInCategoryList = false;
        goToPage(0);
      } else {
        Global.alert.showAlert(this, GameAlert.YES_NO_TYPE, "Bạn có muốn đổi avatar?");
      }
      break;
    case Key.SOFT_RIGHT:
      if (!isInCategoryList) {
        isInCategoryList = true;
      } else {
        Global.nextState(FrmUserInfo.instance(), null);
      }
      break;
    case Key.SOFT_LEFT:
      Global.alert.showAlert1(this, GameAlert.OK_TYPE, StringArray.create1( "Hãy chọn ảnh", "để tải lên" ), 50);
      break;
    case Key.K_1:
    case Key.K_2:
    case Key.K_3:
    case Key.K_4:
    case Key.K_5:
    case Key.K_6:
    case Key.K_7:
    case Key.K_8:
    case Key.K_9:
      int page = keyCode - Key.K_1;
      if (page != currentPage) {
        goToPage(page);
      }
      break;
    case Key.STAR:
      goToPage(currentPage - 1);
      break;
    case Key.POUND:
      goToPage(currentPage + 1);
      break;
    }
  }

  private void goToPage(int page) {
    if (page < 0 || page >= maxPage) {
      return;
    }
    for (int i = 0; i < currentPageAvatarIds.len(); i++) {
      currentPageAvatarIds.array[i] = null;
      requestedAvatar[i] = false;
    }
    currentPage = page;
    avatarChooseIndex = 0;
    SocketClientUtil.getAvatarByCategory(categories.array[categoryChoosedIndex], page * NUMBER_OF_AVATAR_PER_PAGE, (page + 1) * NUMBER_OF_AVATAR_PER_PAGE);
  }
  
  public void onPlatformPictureImport(Platform platform, PlatformPictureImportEvent event) {
    platform.removePictureImportEventHandler(this);
    ByteBuffer byteBuffer = new ByteBuffer();
    event.picture.toBuffer(byteBuffer, Image.FormatPNG);
    byte[] data = new byte[byteBuffer.getLength()];
    for (int i = 0; i < byteBuffer.getLength(); i++) {
      data[i] = byteBuffer.getByte(i);
    }
    ByteArray byteArray = new ByteArray(data, byteBuffer.getLength());
    DataPackage dataPackage = DataPackage.createDataPackage3(ProtocolConstants.RequestHeader.CHANGE_AVATAR_BY_LOCAL_IMAGE_REQUEST, byteBuffer.getLength() + 50);
    dataPackage.putByteArray(byteArray); // number money to paid
    Global.authenClient.write(dataPackage);
  }

  public void alertEventPerform(int alertType, int eventType, int alertId) {
    // Nếu người dùng muốn upload ảnh
    if (alertId == 50) {
      Platform platform = Platform.getInstance();
      platform.addPictureImportEventHandler(this);
      platform.startPictureImport();
    }
    
    // Nếu người dùng đồng ý đổi avtar
    else if (alertType == GameAlert.YES_NO_TYPE && eventType == GameAlert.YES_BUTTON) {
      SocketClientUtil.changeAvatar(currentPageAvatarIds.array[avatarChooseIndex]);
    }
  }
  
  public void destroy() {
    categories = null;
    numberOfAvatarByCategory = null;
    requestedAvatar = null;
    currentPageAvatarIds = null;
    
    leftArrowImage = null;
    leftFocusArrowImage = null;
  }
}